<?php
	class Video extends MY_controller{
		function __construct(){
			parent::__construct();
			$this->load->model('videos');
			$this->load->model('Courses');
		}

		/**
		* 函数功能介绍：返回菜单列表
		* 创建人: 	Yang Ningshu
		* 创建时间: 2014-08-20 16:14
		* 最后修改人：Zhou Hailong
		* 最后修改时间：2014-09-11 16:01
		*/

		function index($review = 0,$activity_id = 0, $sort = 0,$asc_des = 0,$search = 0, $search_type = 1, $is_all = 1,$zid=0, $limit = 0){
			
			if($this->input->post()){
				$limit = 0;
				$post_data = $this->input->post('category');
				$search_type = isset($post_data['search_type']) ? intval($post_data['search_type']) : 1;
				$search = $post_data['search'] ? urldecode($post_data['search']) : 0;
				$review = isset($post_data['review']) ? $post_data['review'] : 0;
				$zid = (isset($post_data['pid'])) ? $post_data['pid'][0] : 0;
				$activity_id = isset($post_data['activity_id']) ? intval($post_data['activity_id']) : 0;
			}else{
				$search = urldecode($search);
				$page_config['uri_segment'] = 11;
			}
			
			$data = array( 'review' => $review, 'activity_id' => $activity_id, 'cate_id'=>$zid,'search_type'=>$search_type, 'sort' => $sort,'asc_des' => $asc_des,'search' => $search,'limit' => $limit);
			$this->smarty->assign("action", '视频管理');
			$offset = 10;
			$current_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
			$result = $this->videos->get_list_ofpage($data['limit'], $offset,$data);
			
			//获取app 活动
			
			/*$this->load->model('activitiess');
			$activity_list = $this->activitiess->get_list(0, 30,  array('type'=>2));*/
			
			$this->load->library('pagination');
			$page_config['base_url'] = '/video/index/'.$data['review'].'/'.$data['activity_id'].'/'.$data['sort'].'/'.$data['asc_des'].'/'.$data['search'].'/'.$search_type.'/'.$is_all.'/'.$data['cate_id'];
			$page_config['total_rows'] = $result['count'];
			$page_config['per_page'] = $offset; 
			$this->pagination->initialize($page_config); 
			$pagination = $this->pagination->create_links();
			$this->smarty->assign("wap_url", $this->config->item('wap_url'));
			$this->smarty->assign("current_url", $current_url);
			$this->smarty->assign("data", $data);
			$this->smarty->assign("is_all", $is_all);
			$this->smarty->assign("video", $result['result']);
			// $this->smarty->assign("activity_list", $activity_list);
			$this->smarty->assign("pagination", $pagination);
			
			
			$cate = $this->Courses->get_cate();
			$subject = $this->Courses->get_course_cate_subject($zid);
			
			$this->smarty->assign("cate", $cate);
			$this->smarty->assign("subject", $subject);
			$this->smarty->display("video/video_list.html");
		}

		/**
		* 函数功能介绍：保存菜单列表
		* 创建人: 	Yang Ningshu
		* 创建时间: 2014-08-20 11:44
		* 最后修改人：
		* 最后修改时间：
		*/
		function save(){
			$data = $this->input->post();
			if(isset($data['image_url'])) $data['image_url'] = get_qiniu_url($data['image_url']);
			unset($data['id']);
			$data['add_time'] = time();
			$result = $this->db->insert('video',$data);
			if($result == TRUE){
				show_message($_SERVER['HTTP_REFERER'], "视频添加成功");
			}else{
				show_message($_SERVER['HTTP_REFERER'], "视频添加失败");
			}
		}


		/**
		* 函数功能介绍：编辑权限菜单
		* 创建人: 	Yang Ningshu
		* 创建时间: 2014-08-20 18:11
		* 最后修改人：
		* 最后修改时间：
		* @param id int
		*/
		function edit($id=0){

			$cate = $this->Courses->get_cate();
			
			if($id){
				$videos_info = $this->videos->get_video_info($id);
				$subject = $this->Courses->get_course_cate_subject($videos_info[0]['cate_id']);
				$token = get_qiniu_token('VIMG');
				
				$this->smarty->assign("token", $token);
				
				$this->smarty->assign("action", '编辑视频信息');
				$this->smarty->assign("cate", $cate);
				$this->smarty->assign("subject", $subject);
				$this->smarty->assign("videos_info", $videos_info[0]);
				$this->smarty->display("video/video_save.html");
			}
			$data = $this->input->post();
			if(isset($data['id'])){
				$data['edit_time'] = time();
				if(isset($data['image_url']) && $data['image_url'] != ''){
					if(isset($data['image_url'])) $data['image_url'] = get_qiniu_url($data['image_url']);
				}
				$data['cate_id'] = (int)$data['cate_id'];
				$data['subject_id'] = (int)$data['subject_id'];
				$this->videos->edit_videos($data);
				if($this->db->affected_rows()){
					show_message($_SERVER['HTTP_REFERER'], "视频修改成功");exit;
				}else{
					show_message($_SERVER['HTTP_REFERER'], "视频修改失败");exit;
				}
			}
			
		}

		/**
		* 函数功能介绍：查看游戏视频信息
		* 创建人: 	Yang Ningshu
		* 创建时间: 2014-08-21 09:44
		* 最后修改人：
		* 最后修改时间：
		* @param id int
		*/
		function view($id){
			$cate = $this->videos->get_video_cate();
			$course = $this->videos->get_course_cate();
			if($id){
				$videos_info = $this->videos->get_video_info($id);
				$this->smarty->assign("action", '查看视频详情');
				$this->smarty->assign("videos_info", $videos_info[0]);
			}
			$this->smarty->assign("cate", $cate);
			$this->smarty->assign("course", $course);
			$this->smarty->display("video/video_view.html");
		}



		/**
		* 函数功能介绍：视频的隐藏和显示
		* 创建人: 	Yang Ningshu
		* 创建时间: 2014-09-2 11:29
		* 最后修改人：
		* 最后修改时间：
		*/
		function status() {
			$return = array();
			if( !$this->input->get() || !$this->input->get('id')) {
				$return = array('code'=>9,'msg'=>'非法操作！');
			}else {
				$get_data = $this->input->get();
				$video_info = get_field_by_where('video', 'id, uid, cate_id', 'id=' . $get_data['id']);
				if(!isset($video_info['id'])){
					echo json_encode(array('code'=>1,'msg'=>'修改失败'));exit;
				}
				if(isset($get_data['live'])){
					$this->db->where('id', $get_data['id']);
 					$this->db->update('video', array('is_live' => $get_data['live']));
				} else if (isset($get_data['is_wb_recommend'])){
					$this->db->where('id', $get_data['id']);
 					$this->db->update('video', array('is_wb_recommend' => $get_data['is_wb_recommend']));
				} else {
					$this->videos->update_video_status($get_data['id'], array('status' => $get_data['status']));
					$this->db->where('top_id', $get_data['id']);
					$this->db->where('type', 3);
					$this->db->update('relation', array('status'=>$get_data['status']));
					$this->load->model("users");
					if($get_data['status'] == 1){
						$this->users->plus_user_video_number($video_info['uid']);
						//增加分类视频数量
						if($video_info['cate_id']>0){
							$this->load->model("m_cate");
							$this->m_cate->increase_count($video_info['cate_id']);
						}
					}else{
						$this->users->reduce_user_video_number($video_info['uid']);
						//减少分类视频数量
						if($video_info['cate_id']>0){
							$this->load->model("m_cate");
							$this->m_cate->reduce_count($video_info['cate_id']);
						}
					}
				}
				if($this->db->affected_rows() > 0) {
					$return = array('code'=>0,'msg'=>'成功修改');
				}else {
					$return = array('code'=>1,'msg'=>'修改失败');
				}
			}
			echo json_encode($return);exit;
		}

		/**
		* 函数功能介绍：视频noov前置
		* 创建人: 	Huang YongJun
		* 创建时间: 2015-06-3 11:29
		* 最后修改人：
		* 最后修改时间：
		*/

		function qiniu_video_add_noov($id){
			require_once ("third_party/qiniu/lib_6_1_13/pfop.php");	
			require_once ("third_party/qiniu/lib_6_1_13/http.php");	
			if(!$id){
				show_message($_SERVER['HTTP_REFERER'], '非法操作');exit;
			}
			$log_rs = get_field_by_where('qiniu_request_log', 'id', 'vid=' . $id.' and status=0');
			if($log_rs){
				show_message($_SERVER['HTTP_REFERER'], '此视频队列正处理，请不要重复操作！');exit;
			}
			$video_info = get_field_by_where('video', 'id,qiniu_video_url,qiniu_id', 'id=' . $id);
			$this->load->model('manage_application');
			$manage_application_list = $this->manage_application->get_list();
			$this->config->load('qiniu_config');
			$data  = $this->config->item('THINK_SDK_QINIU');
			$QINIU_ACCESS_KEY	= $data ['APP_KEY'];
			$QINIU_SECRET_KEY	= $data ['APP_SECRET'];
			$client = new Qiniu_MacHttpClient(null);
			$pfop = new Qiniu_Pfop();
			$pfop->Bucket = $qiniu_config['VIDEO']['UPLOAD_DOMAIN'];
			$pfop->Key = substr($video_info['qiniu_video_url'],strrpos($video_info['qiniu_video_url'],'/')+1);
			$pfop->NotifyURL = $manage_application_list['api_ysx_com']['domain'] . '/qiniu_callback/qiniu_video_add_noov_callback';
			//$persistentId=$video_info['qiniu_id'];
			//$result = Qiniu_PfopStatus($client,$persistentId);
			
			$time_arr = explode(" ", microtime()); 
			$savedKey = md5(gmdate('YmdHis', time()).substr($time_arr[0],2)).time();
			$entry = Qiniu_Encode("$pfop->Bucket:$savedKey");	
			$pfop->Fops = "avthumb/mp4|saveas/$entry";
			list($ret, $err) =$result=$pfop->MakeRequest($client);
			$map['vid']=$id;
			$map['parameter']='|'.$pfop->Bucket.'|'.$pfop->Key.'|'.$savedKey.'|';
			$map['sign']='qiniu_video_add_noov';
			$map['find_sign']=$savedKey;
			$map['cmd']="avthumb/mp4|saveas";
			$map['result']=serialize($result);
			$map['add_time']=time();
			$map['inputKey']='';
			$map['qiniu_id']='';
			if ($err !== null) {
				$map['status']=1;
				$this->db->insert('qiniu_request_log', $map);
				show_message($_SERVER['HTTP_REFERER'], '七牛报错：视频不存在。');exit;
			} else {
				$map['qiniu_id']=$ret['persistentId'];
				$this->db->insert('qiniu_request_log', $map);
				show_message($_SERVER['HTTP_REFERER'], "视频noov前置设置成功，七牛正在处理中！");exit;
			}
		}

		function upload(){
			$this->load->model("Courses");
			$cate = $this->Courses->get_cate();
			$course = $this->videos->get_course_cate();
			$this->smarty->assign("action", '上传视频');
			$this->smarty->assign("video_name", time());
			$this->smarty->assign("cate", $cate);
			$this->smarty->assign("course", $course);
			$this->smarty->display('video/video_save.html');
		}

		public function ignore_get_qiniu_video_token($video_name = '') {
			$upToken = get_qiniu_token('VIDEO', $video_name);
			$data = array ("uptoken" => $upToken );
			exit( json_encode($data));
		}

		function ignore_save_qiniu_data(){
			$post_data = $this->input->post();
			if($post_data){
				print_r($post_data);exit;
				show_message($_SERVER['HTTP_REFERER'], "视频上传成功");
			}
		}
		
		/*function ignore_save_qiniu_data(){
			$post_data = $this->input->post();
			if($post_data){
				$this->config->load('qiniu_config');
				$qiniu_config = $this->config->item('THINK_SDK_QINIU');
				foreach ($post_data as $key => $value) {
					$qiniu_data = json_decode($value['qiniu_return'], true);
					$video_info = get_field_by_where('video', 'id', "qiniu_id = '{$qiniu_data['persistentId']}'");
					if(isset($video_info['id']) && $video_info['id'] > 0){
						show_message($_SERVER['HTTP_REFERER'], "该视频已存在，请勿重复提交");exit;
					}
					$data = $this->get_qiniu_info($qiniu_data['persistentId']);
					$data['uid'] = $value['uid'];
					$data['title'] = $value['title']; 
					$data['qiniu_id'] = $qiniu_data['persistentId'];
					$data['description'] = $value['content'];
					$data['first_letter'] = getfirstchar($data['title']);
					$data['add_time'] = time();
					$data['sort'] = $value['sort'];
					$data['status'] = 1;
					$data['src_type'] = 2;
					$data['base_click'] = $value['base_click'];
					$data['click_num'] = $value['click_num'];
					$data['up_count'] = $value['up_count'];
					if(isset($value['review']) && $value['review'] > 0){
						$data['review'] = $value['review'];
						$data['status'] = 0;
					}
					$this->db->insert('video', $data);
					$vid = $this->db->insert_id();
					if($vid > 0){
						//添加动态数据
						$relation_data = array();
						$relation_data['uid']		= $data['uid'];
						$relation_data['top_id']	= $vid;
						$relation_data['type']		= 3;
						$relation_data['src_type']	= 2;
						$relation_data['status']	= $data['status'];
						$relation_data['up_count']	= 0;
						$relation_data['add_time']	= $data['add_time'];
						
						$this->db->insert("relation", $relation_data);
						
						//增加用户视频数量
						$this->load->model('users');
						$this->users->plus_user_video_number($data['uid']);
					}
				}
				show_message($_SERVER['HTTP_REFERER'], "视频上传成功");
			}
		}*/

		function get_qiniu_info($persistentId = '549a85c27823de406891b37b'){
			$this->config->load('qiniu_config');
			$qiniu_config  = $this->config->item('THINK_SDK_QINIU');
			$return_data = json_decode(@file_get_contents("http://api.qiniu.com/status/get/prefop?id=".$persistentId), true);
			if($return_data['code'] == 0){
				$qiniu_file_info = json_decode(@file_get_contents("http://".$qiniu_config['VIDEO']['DOMAIN_PREFIX'].".".$qiniu_config['VIDEO']['DOMAIN']."/".$return_data['inputKey']."?avinfo"), true);
				$data_arr['image_url'] = "http://".$qiniu_config['VIMG']['DOMAIN_PREFIX'].".".$qiniu_config['VIMG']['DOMAIN']."/".$return_data['items'][0]['key'];
				$data_arr['qiniu_image_key'] = $return_data['items'][0]['key'];
				$data_arr['duration'] = date("H:i:s", mktime(0, 0, $qiniu_file_info['format']['duration']));
				$data_arr['video_size'] = $qiniu_file_info['format']['size'];
				$data_arr['video_url'] = "http://".$qiniu_config['VIDEO']['DOMAIN_PREFIX'].".".$qiniu_config['VIDEO']['DOMAIN']."/".$return_data['inputKey'];
				// print_r($data_arr);
				return $data_arr;
			}else{
				show_message($_SERVER['HTTP_REFERER'], '七牛报错：' . $return_data['items'][0]['error'] . "<br>报错七牛ID：".$persistentId);exit;
			}
		}

		/**
		* 函数功能介绍：重新从七牛获取缩略图
		* 创建人: 	Zhou Hailong
		* 创建时间: 2015-01-23 15:04
		* 最后修改人：
		* 最后修改时间：
		* @param id int
		*/
		function reget_qiniu_info($id){ 
			$video_info = get_field_by_where('video', 'id, image_url, qiniu_video_url, duration, qiniu_id', 'id=' . $id);
			if($video_info['qiniu_id'] != ''){
				$data = $this->get_qiniu_info($video_info['qiniu_id']);
				$this->db->where('id', $id);
				$this->db->update('video', $data);
				show_message($_SERVER['HTTP_REFERER'], "获取数据成功");
			}else{
				show_message($_SERVER['HTTP_REFERER'], "该视频七牛ID数据异常，无法获取数据");
			}
		}

		function duan_video(){
			//最后处理ID：106817
			$sql = "SELECT id, qiniu_video_url, qiniu_id FROM ysx_video WHERE LENGTH(qiniu_video_url)=35 AND qiniu_id != '' AND add_time>1425656236";
			$result = $this->db->query($sql)->result_array();
			// print_r($result);exit;
			foreach ($result as $key => $value) {
				$data = $this->get_qiniu_info($value['qiniu_id']);
				$this->db->where('id', $value['id']);
				$this->db->update('video', $data);
				echo '<br>重新获取'.$value['id'];
			}
		}

		/**
		* 函数功能介绍：删除视频操作
		* 创建人: 	Yang Ningshu
		* 创建时间: 2014-08-21 10:04
		* 最后修改人：Zhang Shaowei
		* 最后修改时间：2014-09-04 10:04
		* @param ids int
		* @param action String
		*/
		function delete($id = 0,$action = ''){
			if($id){
				$result = $this->videos->delete_videos($id);
				if($result == TRUE){
					if($action) {
						show_message($this->input->post('action'), "删除成功");exit;
					}
					show_message($_SERVER['HTTP_REFERER'], "视频删除成功");exit;
				}else{
					echo '错误';
				}
			}else{
				if(!$this->input->post('ids')) {
					$ids = array($id);
				}else {
					$ids = $this->input->post('ids');
				}
				if($ids) {
					foreach($ids as $key=>$val) {
						$this->videos->delete_videos($val);
					}
				}
				if($this->input->post('action')) {
					show_message($this->input->post('action'), "修改成功");exit;
				}
				show_message($_SERVER['HTTP_REFERER'], "视频批量删除成功");
			}
		}


		/**
		* 函数功能介绍：视频批量修改排序
		* 创建人: 	Yang Ningshu
		* 创建时间: 2014-09-02 13:29
		* 最后修改人：
		* 最后修改时间：
		*/
		function update_sorts() {
			$sort = $this->input->post('sort');
			if(is_array($sort)){
				foreach($sort as $key=>$val) {
					$this->videos->update_video_sort($key,array('sort'=>$val));
				}
			}
			if($this->input->post('action')) {
				show_message($this->input->post('action'), "修改成功");exit;
			}
			show_message($_SERVER['HTTP_REFERER'], "视频排序修改成功");
		}

		/**
		* 函数功能介绍：视频鉴黄 $key为七牛视频的key
		* 创建人: 	Zhou Hailong
		* 创建时间: 2015-07-09 11.17
		* 最后修改人：
		* 最后修改时间：
		*/
		function video_nrop(){
			$post_data = $this->input->post();
			if($post_data['key'] == ''){

			}else{
				$this->config->load('qiniu_config');
				$data  = $this->config->item('THINK_SDK_QINIU');
				
				/*return_data返回结果参数说明
				[statistic] => Array([0] => 0[1] => 0 [2] => 10)   这批截图中，按图片识别为 色情、性感、正常 三个分类的数量

			    [result] => normal   视频鉴定类型：色情视频：porn，正常视频：normal，不确定，建议人工复审：review

			    [nonce] => 0.881038686959073  介于0-1间的浮点数，表示该图像被识别为某个分类的概率值，概率越高、机器越肯定；您可以根据您的需求确定需要人工复审的界限。

			    [timestamp] => 1436412254
			    [code] => 0  
			    [message] => success*/
			    $key_list = explode('||', $post_data['key']);
			    $porn_list = array();
			    $review_list = array();
			    foreach ($key_list as $key => $value) {
			    	$video_url = "http://" . $data['VIEW_DOWN_DOMAIN'] . "." . $data['DOMAIN'] . "/" . $value;
			    	$return_data = json_decode(@file_get_contents($video_url . '?tupu-video/nrop'), true);
					if($return_data['result'] == 'porn'){
						//上传的视频可能为色情视频
						$porn_list[] = $key;
						
					}elseif($return_data['result'] == 'review'){
						//建议人工复审
						$review_list[] = $key;
						$result['code'] = 1;
					}else{
						//正常视频
						$result['code'] = 0;
					}
			    }
			    if(count($porn_list) > 0){
			    	$result['code'] = 9;
			    	$result['indexof'] = json_encode($porn_list);
			    }elseif(count($review_list) > 0){
			    	$result['code'] = 1;
			    	$result['indexof'] = json_encode($review_list);
			    }else{
			    	$result['code'] = 0;
			    	$result['indexof'] = '';
			    }
				exit(json_encode($result));
			}
		}

		/**
		* 函数功能介绍：标记非色情视频
		* 创建人: 	Zhou Hailong
		* 创建时间: 2015-07-09 16:10
		* 最后修改人：
		* 最后修改时间：
		*/
		function noreview() {
			$return = array();
			if( !$this->input->get() || !$this->input->get('id')) {
				$return = array('code'=>9,'msg'=>'非法操作！');
			}else {
				$get_data = $this->input->get();
				$this->db->where('id', $get_data['id']);
				$result = $this->db->update('video', array('review' => 0));
				if($this->db->affected_rows() > 0) {
					$return = array('code'=>0,'msg'=>'修改成功');
				}else {
					$return = array('code'=>1,'msg'=>'修改失败');
				}
			}
			echo json_encode($return);exit;
		}
	}